package com.oamicnet.serviceone.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.oamicnet.serviceone.api.account.vo.AccountInfoVO;
import com.oamicnet.serviceone.server.converter.AccountInfoConverter;
import com.oamicnet.serviceone.server.entity.AccountInfo;
import com.oamicnet.serviceone.server.mapper.AccountInfoMapper;
import com.oamicnet.serviceone.server.service.AccountInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

@Service
public class AccountInfoServiceImpl implements AccountInfoService {
    @Autowired
    private AccountInfoConverter accountInfoConverter;

    @Autowired
    private AccountInfoMapper accountInfoMapper;

    @Override
    public AccountInfoVO getByAccountNo(String accountNo) {
        LambdaQueryWrapper<AccountInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AccountInfo::getAccountNo, accountNo);
        return accountInfoConverter.convertAccountInfoToVO(accountInfoMapper.selectOne(wrapper));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateBalance(String accountNo, Double amount) {
        AccountInfoVO accountInfoVO = getByAccountNo(accountNo);
        if (accountInfoVO == null) {
            return 0;
        }

        // 计算新的余额
        BigDecimal newBalance = accountInfoVO.getBalance().add(BigDecimal.valueOf(amount));
        if (newBalance.compareTo(BigDecimal.ZERO) < 0) {
            return 0; // 余额不足
        }

        // 更新余额
        accountInfoVO.setBalance(newBalance);
        AccountInfo accountInfo = accountInfoConverter.convertFromVO(accountInfoVO);
        return accountInfoMapper.updateById(accountInfo);
    }
}
